var express = require('express');
var app = express();
var fs = require("fs");
var path=require("path")

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use('/public', express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));


//注意这个是临时路径,会产生上传的临时文件//不需要的时候最后要删除
app.use(multer({ dest: 'tmp/'}).array('image'));

app.get('/index.htm', function (req, res) {
    res.sendFile( __dirname + path.sep + "index.htm" );
})

app.post('/file_upload', function (req, res) {

    console.log(req.files[0]);  // 上传的文件信息
    //组合要上传到的临时文件夹// path.sep是适应win和linux下的路径分隔符
    var des_file = __dirname + path.sep + req.files[0].originalname;
    console.log("------------",des_file,"---------------")
    fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
            if( err ){
                console.log( err );
            }else{
                response = {
                    message:'File uploaded successfully',
                    filename:req.files[0].originalname
                };
            }
            console.log( response );
            res.writeHead(200,{"content-type":"text/plain;charset=utf-8"});
            res.end( JSON.stringify( response ) );
        });
    });
})

var server = app.listen(8081, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)

})